import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:leader_doctor_flutter/common/http/url_helper.dart';
import 'package:leader_doctor_flutter/common/widget/comm_widget.dart';
import 'package:leader_doctor_flutter/common/widget/refresh_custom_widget.dart';
import 'package:leader_doctor_flutter/common/widget/table_placeholder_widget.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:url_launcher/url_launcher.dart';

import '../../../common/data/app.dart';
import '../../../common/http/api.dart';
import '../../../common/http/http_client.dart';
import '../../../model/study_record.dart';
import '../../../plugins/plugins_messages.g.dart';
import '../../../styles/colors.dart';

/// @Author lixiaobin
/// @Date 2023/11/11
/// @Description 学习记录
class StudyRecordPage extends StatefulWidget {
  const StudyRecordPage({super.key});

  @override
  State<StudyRecordPage> createState() => _StudyRecordPageState();
}

class _StudyRecordPageState extends State<StudyRecordPage> {
  var pageSize = 20;
  var pageNo = 1;
  bool dataLoaded = false; // 数据请求中
  List<StudyRecordModel> items = [];

  final RefreshController _refreshController = RefreshController(initialRefresh: false);

  void _onRefresh() async {
    pageNo = 1;
    _getListPopRecords();
    _refreshController.refreshCompleted();
  }

  void _onLoading() async {
    pageNo++;
    _getListPopRecords();
    _refreshController.loadComplete();
  }

  @override
  initState() {
    super.initState();
    _getListPopRecords();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CommWidget.getCommAppbar(context),
      body: Container(
        color: ColorRes.colorF9F9FA,
        child: SmartRefresher(
            controller: _refreshController,
            enablePullDown: true,
            enablePullUp: true,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: dataLoaded
                ? (items.isEmpty
                    ? TablePlaceholderWidget(
                        message: "暂无数据",
                        yOffset: -30,
                      )
                    : ListView.builder(
                        itemBuilder: (c, i) => _buildItem(items[i]),
                        shrinkWrap: true,
                        itemCount: items.length,
                      ))
                : Container()),
      ),
    );
  }

  Widget _buildItem(StudyRecordModel model) {
    return GestureDetector(
        onTap: () => _jumpDetail(model),
        child: Container(
            margin: EdgeInsets.fromLTRB(10.w, 5.w, 10.w, 5.w),
            padding: EdgeInsets.all(20.w),
            decoration: BoxDecoration(
              color: ColorRes.colorFFFFFF,
              borderRadius: BorderRadius.all(Radius.circular(10.w)),
            ),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(model.title ?? '',
                    maxLines: 2,
                    style: TextStyle(fontSize: 17.sp, color: ColorRes.color333333, fontWeight: FontWeight.w500)),
                SizedBox(height: 12.w),
                Container(color: ColorRes.colorF2F2F2, height: 1),
                SizedBox(height: 12.w),
                Text(model.joinTime ?? '', maxLines: 1, style: TextStyle(fontSize: 13.sp, color: ColorRes.color9A9A9A))
              ],
            )));
  }

  Future<void> _getListPopRecords() async {
    var user = App.instance.userInfo;
    var httpRequest = HttpRequest(Api.listPopRecords, body: {
      'userId': user?.id,
      "userName": user?.realName,
      "pageNo": pageNo.toString(),
      "pageSize": pageSize.toString()
    });
    var httpResponse = await HttpClient.postJson(httpRequest);
    var map = jsonDecode(utf8.decode(httpResponse.raw!.bodyBytes));
    var tmpList = ((map['responseBody'] as List?) ?? []).map((e) => StudyRecordModel.fromJson(e)).toList();
    pageNo == 1 ? items = tmpList : items.addAll(tmpList);
    setState(() {
      dataLoaded = true;
    });
  }

  /// 调转到详情
  _jumpDetail(StudyRecordModel model) async {
    if (model.taskStatus == 'finish') {
      Fluttertoast.showToast(msg: '内容已下线');
      return;
    }
    UrlHelper.loadH5Page(null, model.url ?? '');
  }
}
